package com.example.bingwallpaper.ui

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.bingwallpaper.logic.dao.Image
import com.example.bingwallpaper.logic.dao.ImageResponse
import com.example.bingwallpaper.logic.network.HttpUtil
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class MainViewModel(): ViewModel() {
    val images = MutableLiveData<List<Image>>()
    val currentImage = MutableLiveData<Image>()

    fun getImageUrl() {
        val url: String = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=10"
        HttpUtil.senOkHttpRequest(url, object: Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                if (responseData != null) {
                    Log.d("MyTag", responseData)
                    val _images = parseJSONWithGSON(responseData)
                    for (image in _images) {
                        image.url = "https://cn.bing.com/" + image.url
                    }
                    images.postValue(_images)
                    currentImage.postValue(_images[0])
                }
            }
            override fun onFailure(call: Call, e: IOException) {
                Log.d("MyTag", e.toString())
            }
        })
    }


    fun parseJSONWithGSON(responseData: String): List<Image> {
        val gson = Gson()
        val results = gson.fromJson(responseData, ImageResponse::class.java)
        return results.images
    }




}
